<template>
  <div class="custom_content_style">
    <el-row style="padding: 10px 10px 0px 0px" justify="end">
      <el-tooltip popper-class="custom-tooltip" :hide-after="0" placement="bottom">
        <template #content>
          <span class="custom-tooltip">导入</span>
        </template>
        <el-upload action="#" :http-request="importEmpInfo" :show-file-list="false" :before-upload="beforeUpload">
          <template #trigger>
            <el-button class="normal-button" icon="Upload" text />
          </template>
        </el-upload>
      </el-tooltip>
      <el-tooltip popper-class="custom-tooltip" :hide-after="0" placement="bottom">
        <template #content>
          <span class="custom-tooltip">导出</span>
        </template>
        <el-button class="normal-button" icon="Download" @click="exportEmpInfo" text />
      </el-tooltip>
      <el-tooltip popper-class="custom-tooltip" :hide-after="0" placement="bottom">
        <template #content>
          <span class="custom-tooltip">新建</span>
        </template>
        <el-button class="normal-button" icon="Plus" @click="addEmpInfo" text />
      </el-tooltip>
      <el-tooltip popper-class="custom-tooltip" v-if="multipEmpInfoSelection.length > 0" :hide-after="0" placement="bottom">
        <template #content>
          <span class="custom-tooltip">删除</span>
        </template>
        <el-button class="normal-button" icon="DeleteFilled" @click="deleteEmpInfo" text />
      </el-tooltip>
      <el-tooltip popper-class="custom-tooltip" v-if="multipEmpInfoSelection.length === 1" :hide-after="0" placement="bottom">
        <template #content>
          <span class="custom-tooltip">编辑</span>
        </template>
        <el-button class="normal-button" icon="EditPen" @click="editEmpInfo" text />
      </el-tooltip>
      <el-tooltip popper-class="custom-tooltip" :hide-after="0" placement="bottom">
        <template #content>
          <span class="custom-tooltip">刷新</span>
        </template>
        <el-button
          class="normal-button"
          icon="RefreshRight"
          @click="queryEmpInfo"
          text
          :loading="refreshLoading"
          loading-icon="RefreshRight" />
      </el-tooltip>
    </el-row>
    <el-row style="padding: 10px">
      <el-table
        :data="empInfoData"
        highlight-current-row
        @selection-change="empInfoSelectionChange"
        :header-cell-style="{ background: '#f2f2f2', color: '#1f2937', fontWeight: 'bold' }"
        :height="activeHeight"
        stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="#" width="60" fixed />
        <el-table-column label="工作证号" prop="empNo" width="100" fixed>
          <template #header>
            <el-row align="middle">
              <span>工作证号</span>
              <dec-filter filter-type="text" :filter-width="100" @filter-change="empNoFilterChange"></dec-filter>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="empName" width="110" fixed>
          <template #header>
            <el-row align="middle">
              <span>姓名</span>
              <dec-filter filter-type="text" :filter-width="100" @filter-change="empNameFilterChange"></dec-filter>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="empDepartment" width="100">
          <template #header>
            <el-row align="middle">
              <span>部门</span>
              <dec-filter filter-type="text" :filter-width="100" @filter-change="empDepartmentFilterChange"></dec-filter>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="聘用形式" prop="empType" width="180">
          <template #header>
            <el-row align="middle">
              <span>聘用形式</span>
              <dec-filter filter-type="text" :filter-width="200" @filter-change="empTypeFilterChange"></dec-filter>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="籍贯" prop="empNativePlace" width="150" />
        <el-table-column label="出生日期" prop="empBrithday" width="120" />
        <el-table-column label="身份证号" prop="empCardId" width="200" />
        <el-table-column label="进入时间" prop="empEntryTime" width="120" />
        <el-table-column label="职称资格" prop="empProfessionalTitle" width="120" />
        <el-table-column label="学历" prop="empDegree" width="100" />
        <el-table-column label="所学专业" prop="empProfessional" width="200" show-overflow-tooltip />
        <el-table-column label="毕业学校" prop="empUniversity" width="200" />
        <el-table-column label="职务名称" prop="empJobTitle" width="200" />
        <el-table-column label="政治面貌" prop="empPoliticalLook" />
        <el-table-column label="执业资质名称" prop="empQualificationTitle" width="150" />
        <el-table-column label="备注" prop="empRemark" width="100" show-overflow-tooltip />
      </el-table>
    </el-row>
    <el-row style="padding: 10px 10px 10px 0px" justify="end">
      <el-popover
        :visible="pagePopoverVisible"
        placement="top"
        width="80px"
        :popper-style="{ minWidth: '0px', padding: '5px' }"
        :hide-after="0">
        <template #reference>
          <el-button
            class="page-button"
            style="border-radius: 8px 0px 0px 8px"
            text
            @click="pagePopoverVisible = true"
            @blur="pagePopoverVisible = false">
            {{ pageSize }}<el-icon class="page-icon"><CaretBottom /></el-icon>条每页
          </el-button>
        </template>
        <el-row>
          <el-button
            v-for="item in [50, 100, 150]"
            class="normal-button"
            :style="{
              fontSize: '12px',
              width: '100%',
              color: item === pageSize ? '#409eff' : '',
            }"
            @click="handleSizeChange(item)"
            text>
            <div style="width: 50px; display: flex; justify-content: space-between">
              <span>{{ item }}</span>
              <el-icon v-show="item === pageSize" style="margin-left: 5px; color: #409eff"><CircleCheck /></el-icon>
            </div>
          </el-button>
        </el-row>
      </el-popover>
      <el-button class="page-button" @click="handleCurrentChange('start')" text>
        <el-icon style="transform: rotate(90deg)"><Download /></el-icon>
      </el-button>
      <el-button class="page-button" icon="ArrowLeft" @click="handleCurrentChange(-1)" text />
      <el-button class="page-button" text>第 {{ pageNum }} 页</el-button>
      <el-button class="page-button" text>共 {{ totalPage }} 页</el-button>
      <el-button class="page-button" icon="ArrowRight" text @click="handleCurrentChange(1)" />
      <el-button class="page-button" @click="handleCurrentChange('end')" text>
        <el-icon style="transform: rotate(-90deg)"><Download /></el-icon>
      </el-button>
      <el-button class="page-button" style="border-radius: 0px 8px 8px 0px" text>共 {{ total }} 条</el-button>
      <!-- <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :total="total"
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[50, 100, 150]"
        layout="sizes, prev, pager, next, jumper, ->, total, slot"
        :background="true">
      </el-pagination> -->
    </el-row>
    <el-dialog
      style="border-radius: 15px"
      v-model="empInfoVisible"
      :close-on-click-modal="false"
      title="员工信息"
      width="40%"
      @close="closeEmpInfoDialog(empInfoFormRef)"
      draggable>
      <el-scrollbar max-height="600px" :always="true">
        <el-form style="margin-right: 20px" ref="empInfoFormRef" :model="empInfoForm" :rules="rules" :inline="true" label-width="120px">
          <el-form-item label="工作证号" prop="empNo">
            <el-input v-model="empInfoForm.empNo"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="empName">
            <el-input v-model="empInfoForm.empName"></el-input>
          </el-form-item>
          <el-form-item label="部门">
            <el-input v-model="empInfoForm.empDepartment"></el-input>
          </el-form-item>
          <el-form-item label="聘用形式">
            <el-input v-model="empInfoForm.empType"></el-input>
          </el-form-item>
          <el-form-item label="籍贯">
            <el-input v-model="empInfoForm.empNativePlace"></el-input>
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="empInfoForm.empCardId"></el-input>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker v-model="empInfoForm.empBrithday" type="date" style="width: 192px"></el-date-picker>
          </el-form-item>
          <el-form-item label="进入时间">
            <el-date-picker v-model="empInfoForm.empEntryTime" type="date" style="width: 192px"></el-date-picker>
          </el-form-item>
          <el-form-item label="职称资格">
            <el-input v-model="empInfoForm.empProfessionalTitle"></el-input>
          </el-form-item>
          <el-form-item label="学历">
            <el-input v-model="empInfoForm.empDegree"></el-input>
          </el-form-item>
          <el-form-item label="所学专业">
            <el-input v-model="empInfoForm.empProfessional"></el-input>
          </el-form-item>
          <el-form-item label="毕业学校">
            <el-input v-model="empInfoForm.empUniversity"></el-input>
          </el-form-item>
          <el-form-item label="职务名称">
            <el-input v-model="empInfoForm.empJobTitle"></el-input>
          </el-form-item>
          <el-form-item label="政治面貌">
            <el-input v-model="empInfoForm.empPoliticalLook"></el-input>
          </el-form-item>
          <el-form-item label="执业资质名称">
            <el-input v-model="empInfoForm.empQualificationTitle"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="empInfoForm.empRemark"></el-input>
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <el-row justify="end">
        <el-button class="dialog-button" @click="closeEmpInfoDialog(empInfoFormRef)" text>取消</el-button>
        <el-button class="dialog-button" @click="resetEmpInfo(empInfoFormRef)" text>重置</el-button>
        <el-button class="submit-button" type="primary" @click="submitEmpInfo(empInfoFormRef)" text>提交</el-button>
      </el-row>
    </el-dialog>
    <el-dialog style="border-radius: 15px" v-model="importDialogVisible" :close-on-click-modal="false" title="错误信息" width="40%">
      <el-text type="danger" size="large" style="white-space: pre-wrap; line-height: 20px">{{ importErrorMsg }}</el-text>
      <el-row justify="end">
        <el-button class="dialog-button" @click="importDialogVisible = false" text>关闭</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox, dayjs } from "element-plus";
import EmpInfoService from "@/https/api/empinfo";
import decFilter from "@/components/decFilter.vue";

const activeHeight = ref(0);
onMounted(() => {
  activeHeight.value = document.querySelector(".custom_content_style").clientHeight - 120;
  // window.addEventListener("resize", () => {
  //   activeHeight.value = document.querySelector(".custom_content_style").clientHeight - 120;
  // });
  queryEmpInfo();
});

const empInfoData = ref([]);
const refreshLoading = ref(false);
const pageNum = ref(1);
const pageSize = ref(50);
const total = ref(0);
const totalPage = ref(1);
const pagePopoverVisible = ref(false);
const empInfoConditions = ref({});

const queryEmpInfo = async () => {
  refreshLoading.value = true;
  const res = await EmpInfoService.queryEmpInfo({
    empInfoConditions: empInfoConditions.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  });
  if (res.code === 200) {
    empInfoData.value = res.data.records;
    total.value = res.data.total;
    totalPage.value = Math.ceil(total.value / pageSize.value);
    refreshLoading.value = false;
  } else {
    ElMessage.error("系统异常");
  }
};

const handleSizeChange = (param) => {
  pageSize.value = param;
};

watch(pageSize, () => {
  queryEmpInfo();
});

const handleCurrentChange = (param) => {
  if (typeof param === "number" && total.value > 0) {
    const res = pageNum.value + param;
    if (res < 1) {
      pageNum.value = 1;
    } else if (res > totalPage.value) {
      pageNum.value = totalPage.value;
    } else {
      pageNum.value = res;
    }
  } else if (typeof param === "string") {
    if (param === "start") {
      pageNum.value = 1;
    } else if (param === "end") {
      pageNum.value = Math.ceil(total.value / pageSize.value);
      pageNum.value = pageNum.value === 0 ? 1 : pageNum.value;
    }
  }
};

watch(pageNum, () => {
  queryEmpInfo();
});

const multipEmpInfoSelection = ref([]);

const empInfoSelectionChange = (val) => {
  multipEmpInfoSelection.value = val;
};

// 工作证号过滤
const empNoFilterChange = (val) => {
  empInfoConditions.value.empNo = val;
  queryEmpInfo();
};

// 姓名过滤
const empNameFilterChange = (val) => {
  empInfoConditions.value.empName = val;
  queryEmpInfo();
};

// 部门过滤
const empDepartmentFilterChange = (val) => {
  empInfoConditions.value.empDepartment = val;
  queryEmpInfo();
};

// 聘用形势过滤
const empTypeFilterChange = (val) => {
  empInfoConditions.value.empType = val;
  queryEmpInfo();
};

const empInfoVisible = ref(false);
const empInfoForm = ref({});
const empInfoFormRef = ref();
const empNoUniqueCheck = (rule, value, callback) => {
  if (value && value.length > 0) {
    EmpInfoService.uniqueCheck({ id: empInfoForm.value.id, empNo: value }).then((res) => {
      if (res.code === 200 && res.data?.id) {
        callback(new Error("该工作证号已存在"));
      } else {
        callback();
      }
    });
  } else {
    callback();
  }
};
const rules = {
  empNo: [
    { required: true, message: "请输入工作证号", trigger: "blur" },
    { validator: empNoUniqueCheck, trigger: "blur" },
  ],
  empName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
};

const beforeUpload = (file) => {
  if (file.size / 1024 / 1024 / 1024 > 1) {
    ElMessage.error("文件大小不能超过1GB");
    return false;
  } else if (!file.name.endsWith(".xls") && !file.name.endsWith(".xlsx")) {
    ElMessage.error("文件格式只能是xls、xlsx");
    return false;
  }
};

const importDialogVisible = ref(false);
const importErrorMsg = ref("");
const importEmpInfo = (options) => {
  let fd = new FormData();
  fd.append("file", options.file);
  EmpInfoService.importEmpInfo(fd).then((res) => {
    if (res.code === 200) {
      ElMessage.success("保存成功");
      queryEmpInfo();
    } else if (res.code === 600) {
      importErrorMsg.value = res.msg;
      if (res.data) {
        importErrorMsg.value += "\n请下载错误Excel更改后，重新导入。";
        EmpInfoService.exportCorrect(res.data).then((res) => {
          const blob = new Blob([res]);
          const fileName = "更正主项Excel.xlsx";
          const elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          URL.revokeObjectURL(elink.href);
          document.body.removeChild(elink);
        });
      } else {
        importErrorMsg.value += "\n请检查后，重新导入。";
      }
      importDialogVisible.value = true;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const exportEmpInfo = async () => {
  let res = await EmpInfoService.exportEmpInfo(multipEmpInfoSelection.value).then((res) => {
    console.log(res);
    const blob = new Blob([res]);
    const elink = document.createElement("a");
    elink.download = "采购人员信息表.xlsx";
    elink.style.display = "none";
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href);
    document.body.removeChild(elink);
  });
};

const addEmpInfo = () => {
  empInfoVisible.value = true;
};

const deleteEmpInfo = () => {
  if (multipEmpInfoSelection.value.length === 0) return;
  ElMessageBox.confirm(`确定删除选中的${multipEmpInfoSelection.value.length}条数据吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "我再想想",
    type: "error",
  }).then(() => {
    const ids = multipEmpInfoSelection.value.map((item) => item.id);
    EmpInfoService.deleteEmpInfo({ ids: ids }).then((res) => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        queryEmpInfo();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};

const editEmpInfo = () => {
  empInfoVisible.value = true;
  empInfoForm.value = { ...multipEmpInfoSelection.value[0] };
};

const closeEmpInfoDialog = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  empInfoForm.value = {};
  empInfoVisible.value = false;
};

const submitEmpInfo = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      EmpInfoService.saveEmpInfo({ empInfo: empInfoForm.value }).then((res) => {
        if (res.code === 200) {
          ElMessage.success("保存成功");
          queryEmpInfo();
          closeEmpInfoDialog(formEl);
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
};

const resetEmpInfo = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  if (empInfoForm.value.id) {
    empInfoForm.value = { ...multipEmpInfoSelection.value[0] };
  } else {
    empInfoForm.value = {};
  }
};
</script>
<style scoped>
.custom_content_style {
  background-color: white !important;
  height: calc(100vh - 100px);
}
.normal-button,
.page-button,
.dialog-button {
  margin: 0px;
  color: #1f2937;
  padding: 8px;
}
.submit-button:hover {
  background-color: #d6eaf2 !important;
}
.normal-button:hover,
.page-button:hover,
.dialog-button:hover {
  background-color: #d2d4d7 !important;
}
.normal-button {
  font-size: 20px;
}
.page-button {
  padding: 0px 15px 0px 15px;
  border-radius: 0px;
  font-size: 14px;
  font-weight: 600;
}
.dialog-button,
.submit-button {
  padding: 0px 15px 0px 15px;
  font-size: 14px;
  font-weight: 600;
}
.submit-button {
  margin: 0px;
}
.page-icon {
  margin: 4px;
  font-size: 10px;
}
.custom-tooltip {
  color: #d8dde4 !important;
}
</style>
